﻿using CamstarAPI;
using Infragistics.WebUI.UltraWebGrid;
using IntegrationAgent;
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using uMES.LeanManufacturing.ParameterDTO;
using uMES.LeanManufacturing.ReportBusiness;
using uMES.LeanManufacturing.DBUtility;

public partial class ReplaceMaterialInfoForm :BaseForm
{
    uMESMaterialBusiness material = new uMESMaterialBusiness();
    uMESContainerBusiness containerBal = new uMESContainerBusiness();
    uMESCommonBusiness common = new uMESCommonBusiness();
    ERPWebService erp = new ERPWebService();
    string businessName = "生产准备", parentName = "Container";
    int m_PageSize = 30;
    protected void Page_Load(object sender, EventArgs e)
    {
        upageTurning.PageIndexChanged += new pageTurning.PageIndexChangedEventHandler(() => { SearchData(upageTurning.CurrentPageIndex); });
    }

    #region 事件
    protected void btnSearch_Click(object sender, EventArgs e)
    {
        try
        {
            //ResetData(true, true);
            SearchData(1);
        }
        catch (Exception ex)
        {
            DisplayMessage(ex.Message, false);
        }
    }


    protected void btnReSet_Click(object sender, EventArgs e)
    {
        try
        {
           // ResetData(true, true);
        }
        catch (Exception ex)
        {
            DisplayMessage(ex.Message, false);
        }
    }

    protected void Button1_Click(object sender, EventArgs e)
    {
        try
        {
            ClearMessage();

            UltraGridRow uldr = wgContainer.DisplayLayout.ActiveRow;
            if (uldr == null)
            {
                DisplayMessage("请选择记录", false);
                return;
            }

            DataTable poupDt = new DataTable();
            poupDt.Columns.Add("ProductID");
            poupDt.Columns.Add("WorkflowID"); poupDt.Columns.Add("ContainerID"); poupDt.Columns.Add("ContainerName");
            DataRow newRow = poupDt.NewRow();
            newRow["ProductID"] = uldr.Cells.FromKey("ProductID").Text;
            newRow["WorkflowID"] = uldr.Cells.FromKey("WorkflowID").Text;
            newRow["ContainerID"] = uldr.Cells.FromKey("ContainerID").Text;
            newRow["ContainerName"] = uldr.Cells.FromKey("ContainerName").Text;
            poupDt.Rows.Add(newRow);
            Session.Add("ProcessDocument", poupDt);
            
            var page = "Custom/bwCommonPage/uMESDocumentViewPopupForm.aspx";
          //  var script = String.Format("<script>OpenPopupWindow(false,'{0}','dialogWidth={1}px;dialogHeight={2}px;status=0');</script>", page, 700, 600);
           // Infragistics.WebUI.Shared.CallBackManager.AddScriptBlock(Page, WebAsyncRefreshPanel1, script);

            ShowPopupPage(page,700,600,true);
        }
        catch (Exception ex)
        {
            DisplayMessage(ex.Message, false);
        }
    }

    /// <summary>
    /// 查询erp库存
    /// </summary>
    /// <param name="sender"></param>
    /// <param name="e"></param>
    protected void btnErpSearch_Click(object sender, EventArgs e)
    {
        try
        {
            SearErpMaterial();
        }
        catch (Exception ex)
        {
            DisplayMessage(ex.Message, false);
        }
    }

    protected void btnSave_Click(object sender, EventArgs e)
    {
        try
        {
            var re = SaveReplaceMaterial();
            if (re.IsSuccess)
            {
                ContainerExcuteLog("代料信息成功");
                SearchData(1);
                DisplayMessage("保存成功", true );
            }
            else {
                DisplayMessage(re.Message,false);
            }
               
        }
        catch (Exception ex)
        {
            DisplayMessage(ex.Message, false);
        }
    }

    protected void btnSave2_Click(object sender, EventArgs e)
    {
        try
        {
            var re = SaveContainerDoc();
            if (re.IsSuccess)
            {
                ContainerExcuteLog(",附件保存成功");
                SearchData(1);
                DisplayMessage("保存成功", true );
            }
            else
            {
                DisplayMessage(re.Message, false);
            }

        }
        catch (Exception ex)
        {
            DisplayMessage(ex.Message, false);
        }
    }
    #endregion

    #region 方法
    void SearchData(int index) {
        wgContainer.Rows.Clear();
        Dictionary<string, string> para = new Dictionary<string, string>();
        if (!string.IsNullOrWhiteSpace(txtProcessNo.Text)) {
            para["ProcessNo"] = txtProcessNo.Text;
        }
        if (!string.IsNullOrWhiteSpace(txtContainerName.Text))
        {
            para["ContainerName"] = txtContainerName.Text;
        }
        para["CurrentPageIndex"] = index.ToString();
        para["PageSize"] = m_PageSize.ToString();
        uMESPagingDataDTO result = material.GetReplaceMaterialContainer(para);

        this.wgContainer.DataSource = result.DBTable;
        this.wgContainer.DataBind();

        //给分页控件赋值，用于分页控件信息显示
        this.upageTurning.TotalRowCount = int.Parse(result.RowCount);
        this.upageTurning.RowCountByPage = m_PageSize;
    }

    /// <summary>
    /// 查询erp库存
    /// </summary>
    void SearErpMaterial() {
        Dictionary<string, string> para = new Dictionary<string, string>();
        wgReplaceMaterial.Rows.Clear();
        para["material"] = txtErpMaterial.Text;
        para["MaterialName"] = txtErpMaterialName.Text;

        if (string.IsNullOrWhiteSpace(para["material"]) && string.IsNullOrWhiteSpace(para["MaterialName"])) {
            DisplayMessage("请输入条件",false);
            return;
        }

        if (erp.Login())
        {
            string strMsg = "";
            DataTable dt = erp.GetMaterialInfo(para, out strMsg);

            wgReplaceMaterial.DataSource = dt;
            wgReplaceMaterial.DataBind();
        }

    }

    /// <summary>
    /// 保存代料信息
    /// </summary>
    /// <returns></returns>
    ResultModel SaveReplaceMaterial() {
        ResultModel re = new ResultModel(false,"");

        UltraGridRow activeContainer = wgContainer.DisplayLayout.ActiveRow;
        UltraGridRow activeMaterial = wgReplaceMaterial.DisplayLayout.ActiveRow;

        if (activeContainer == null || activeMaterial == null) {
            re.Message = "请选择批次和原材料！";
            return re;
        }
        if (string.IsNullOrWhiteSpace(txtReplaceMaterialQty.Text)) {
            re.Message = "请输入所需代料数！";
            return re;
        }
        //有代料信息的不能维护
        if (!string.IsNullOrWhiteSpace(activeContainer.Cells.FromKey("ReplaceMaterial").Text)) {
            re.Message = "批次已有代料信息！";
            return re;
        }

        var p_dataEntityList = new List<ClientAPIEntity>();

        ClientAPIEntity entity = new ClientAPIEntity("代料规格型号",DataTypeEnum.DataField,activeMaterial.Cells.FromKey("ReplaceMaterial").Text,"");
        p_dataEntityList.Add(entity);

        entity = new ClientAPIEntity("代料名称", DataTypeEnum.DataField, activeMaterial.Cells.FromKey("MaterialName").Text, "");
        p_dataEntityList.Add(entity);

        entity = new ClientAPIEntity("代料数", DataTypeEnum.DataField, txtReplaceMaterialQty.Text, "");
        p_dataEntityList.Add(entity);

        var api = new CamstarClientAPI(UserInfo["ApiEmployeeName"],UserInfo["ApiPassword"]);

        string strMsg = "";
        re.IsSuccess = api.ContainerAtterMaint(activeContainer.Cells.FromKey("ContainerName").Text,activeContainer.Cells.FromKey("ContainerLevelName").Text, p_dataEntityList,ref strMsg);
        re.Message = strMsg;
        return re;

    }

    /// <summary>
    /// 保存批次附件
    /// </summary>
    /// <returns></returns>
    ResultModel SaveContainerDoc() {
        ResultModel re = new ResultModel(false, "");
        UltraGridRow activeContainer = wgContainer.DisplayLayout.ActiveRow;
        if (activeContainer == null)
        {
            re.Message = "请选择批次记录！";
            return re;
        }
        //有代料信息的不能维护
        if (string.IsNullOrWhiteSpace(activeContainer.Cells.FromKey("ReplaceMaterial").Text))
        {
            re.Message = "批次未维护代料信息！";
            return re;
        }
        var strPath = bffSelectPath.FileName;

        if (string.IsNullOrWhiteSpace(strPath))
        {
            return new ResultModel(false, "请选择附件");
        }
        string fileName = SaveFileToServer(ref strPath );
        //挂附件
        Dictionary<string, string> para = new Dictionary<string, string>();
        para["ckattachmentname"] = fileName;
        para["ckattachtype"] = "其他";
        para["ckurl"] = strPath;
        para["ContainerID"] = activeContainer.Cells.FromKey("ContainerID").Text;

        material.SaveContainerDoc(para);

        re.IsSuccess = true;
        SendToErpAgain(activeContainer);
        return re;
    }

    /// <summary>
    /// 保存到服务器
    /// </summary>
    /// <param name="strpath"></param>
    /// <returns></returns>
    string SaveFileToServer(ref string strpath)
    {

        var fileName = strpath.Substring(strpath.LastIndexOf(@"\") + 1);
        

        strpath = ConfigurationManager.AppSettings["AccessoriesHTTPPath"] + fileName;
        bffSelectPath.SaveAs(strpath);

        bffSelectPath.Dispose();

        return fileName;
    }

    /// <summary>
    /// 重新发送零件批次的物料申请
    /// </summary>
    /// <param name="row"></param>
    void SendToErpAgain(UltraGridRow row) {
        string containerId = row.Cells.FromKey("ContainerID").Text;
        string workflowId = row.Cells.FromKey("WorkflowID").Text;

        //代料信息和附件同时存在的情况下才重推
        if (containerBal.GetTableInfo("ckattachment", "containerid", containerId).Rows.Count == 0)
        {
            return;
        }
        if (containerBal.GetTableInfo("userattribute", "parentid", containerId).Rows.Count == 0) {
            return;
        }

        OracleHelper.ExecuteDataByEntity(new ExcuteEntity("materialappinfo", ExcuteType.update) {
            ExcuteFileds=new List<FieldEntity>() { new FieldEntity("issenderp","0",FieldType.Numer)},
            WhereFileds=new List<FieldEntity>() { new FieldEntity("containerid", containerId, FieldType.Str), new FieldEntity("workflowId", workflowId, FieldType.Str) }
        });
    }

    /// <summary>
    /// 日志记录
    /// </summary>
    /// <param name="ml"></param>
    void ContainerExcuteLog(string strMsg)
    {
        var ml =new MESAuditLog();
        UltraGridRow activeContainer = wgContainer.DisplayLayout.ActiveRow;
        ml.ContainerID= activeContainer.Cells.FromKey("ContainerID").Text; 
        ml.ContainerName= activeContainer.Cells.FromKey("ContainerName").Text;

        ml.ParentName = parentName; ml.BusinessName = businessName;
        ml.CreateEmployeeID = UserInfo["EmployeeID"]; ml.ParentID = ml.ContainerID;

        ml.Description = "批次代料信息维护:"+strMsg;
        common.SaveMESAuditLog(ml);
    }
    #endregion






}